﻿using WorldMapBase;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;


/// <summary>
/// 简单粗暴的Sample
/// </summary>
public class SampleObjectLayer : SimpleAbstractLODLayer
{
    public interface ISampleObjectLayerListener
    {
        void OnObjectVisibleChange(int id, bool isHide);
    }

    public class LayerObject
    {
        public int id
        {
            get
            {
                return m_Data.id;
            }
        }

        public Vector2 pos
        {
            get
            {
                return m_Data.pos;
            }
        }

        internal bool hideFlag = true;
        private ObjectData m_Data;

        public LayerObject(ObjectData data)
        {
            m_Data = data;
        }
    }


    private ISampleObjectLayerListener m_Listener;
    private List<LayerObject> m_ObjList = new List<LayerObject>();
    private bool b_FirstRuntime;

    public SampleObjectLayer(ISampleObjectLayerListener listener)
    {
        SetListener(listener);
    }

    public void AddObject(LayerObject obj)
    {
        m_ObjList.Add(obj);
    }

    public void RemoveObject(LayerObject obj)
    {
        m_ObjList.Remove(obj);
    }

    public void SetListener(ISampleObjectLayerListener listener)
    {
        m_Listener = listener;
    }

    protected override void OnCreate()
    {
        b_FirstRuntime = true;
    }

    protected override void OnDestroy()
    {
        b_FirstRuntime = false;
    }

    protected override void OnUpdateViewRect(int4 viewRect)
    {
        // Debug.Log(string.Format("xxxxxxxxxxx 视图范围 {0}", viewRect));
        var lbViewPos = viewRect.xy;
        var rtViewPos = lbViewPos + viewRect.zw;

        for (int i = 0, cnt = m_ObjList.Count; i < cnt; i++)
        {
            var obj = m_ObjList[i];
            var newHideFlag = !(obj.pos.x > lbViewPos.x && obj.pos.x < rtViewPos.x && obj.pos.y > lbViewPos.y && obj.pos.y < rtViewPos.y);
            if (b_FirstRuntime)
            {
                m_Listener.OnObjectVisibleChange(obj.id, newHideFlag);
                obj.hideFlag = newHideFlag;
                b_FirstRuntime = false;
            }
            else
            {
                // Debug.Log(string.Format("id {0} 位置 {1} 显示 {2}", id, obj.pos, !newHideFlag));

                if (obj.hideFlag != newHideFlag)
                {
                    m_Listener.OnObjectVisibleChange(obj.id, newHideFlag);
                    obj.hideFlag = newHideFlag;
                }
            }

        }
    }

    public override void OnLODLevelChange(int currentLodLevel, int lastLodLevel)
    {
        // TODO LOD等级改变做的事
    }

    public override void OnNextLODPercentUpdate(int lodLevel, float nextLevelPercent)
    {
        // TODO LOD百分比变化时做的事
    }
}
